import { ref } from "vue";
import { getCommentById, addComment as addCommentApi, deleteComment as deleteCommentApi } from "@/api/modules/sys";
import { dialogForm } from "@/utils/dialogForm";
import { useHandleData } from "@/hooks/useHandleData";
import { useDict } from "@/hooks/useDict";
export const useComments = () => {
  const { getDict } = useDict();
  let params: any = ref({
    searchKey: "",
    typeId: 0,
    currentPage: 1,
    pageSize: 100,
    relatedId: 0,
    userId: 0
  });
  let drawerVisible = ref(false);
  let config = ref<any>({ width: 60 });
  const getCommentByIdFn = async (relatedId: string) => {
    const { data } = await getCommentById({ ...params.value, relatedId });
    return data;
  };

  const addComment = async (options: any, obj: any) => {
    const { relatedId, relatedTitle } = options;
    drawerVisible.value = true;
    config.value.message = "添加成功";
    config.value.title = "添加评论";
    config.value.form = {
      formData: {
        content: "",
        relatedId,
        relatedTitle,
        typeId: getDict("answerType")
      },
      rules: {
        content: [{ required: true, message: "请填写评论内容" }]
      }
    };
    config.value.column = [
      {
        type: "input",
        key: "content",
        formItemAttribute: {
          label: "评论内容"
        },
        attributes: {
          placeholder: "请填写评论内容",
          type: "textarea",
          rows: 5
        }
      }
    ];
    config.value.api = addCommentApi;
    config.value.transformData = (data: any) => {
      return data;
    };
    dialogForm({
      config: config.value,
      drawerVisible: drawerVisible.value,
      successCallback: async () => {
        params.value.currentPage = 1;
        const data = await getCommentByIdFn(relatedId);
        obj.commentList = (data && data.records) || [];
      }
    });
  };

  // 删除评论
  const deleteComment = async (option: any, obj: any) => {
    const { id, relatedId } = option;
    await useHandleData(deleteCommentApi, { id }, `删除评论`);
    params.value.currentPage = 1;
    const data = await getCommentByIdFn(relatedId);
    obj.commentList = (data && data.records) || [];
  };

  return {
    getCommentByIdFn,
    addComment,
    deleteComment
  };
};
